package chu.dejian.ui.fragmet;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import com.sam.ui.base.fragment.BaseFragment;
import com.sam.utils.NetUtil;
import com.sam.utils.display.DensityUtils;
import com.sam.utils.L;
import com.sam.utils.T;
import com.sam.widget.badge.BadgeView;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenu;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuCreator;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuItem;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;
import chu.dejian.adapter.AttentionWithBadgeAdapter;
import chu.dejian.db.DBHelper;
import chu.dejian.entity.AttendeeEntity;
import chu.dejian.entity.ContactEntity;
import chu.dejian.entity.MeasureMessageEntity;
import chu.dejian.entity.ReceivedRequestEntity;
import chu.dejian.models.GetAttendeesResponse;
import chu.dejian.models.GetAttenderMessagesResponse;
import chu.dejian.models.GetReceivedAttenderRequestResponse;
import chu.dejian.models.PutAttendeesRequest;
import chu.dejian.restApi.RestClient;
import chu.dejian.ui.activity.MeasureMessageActivity;
import chu.dejian.ui.activity.ReceivedRequestActivity;
import chu.dejian.widget.AttentionLevelView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MyAttentionFragment extends BaseFragment{
	private static MyAttentionFragment instance;
	private AttentionWithBadgeAdapter attendeeAdapter;
	private List<ContactEntity> attendeeList;
	private List<ContactEntity> attentionRequestList = new ArrayList<>();
	private List<ContactEntity> newAttentionRequests = new ArrayList<>();
	private List<MeasureMessageEntity> measureMessageList = new ArrayList<>();
	private List<MeasureMessageEntity> newMessageList = new ArrayList<>();
	private SwipeMenuListView attentionContactListView;
	private AnsyncDataThread ansyncDataThread = new AnsyncDataThread();
	private boolean attendeeUpdated;
	private TextView newRequestItem;

	public synchronized static MyAttentionFragment getInstance(){
		if(instance == null){
			instance = new MyAttentionFragment();
		}
		return instance;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_my_attention);
	}

	public void findView() {
		attentionContactListView = (SwipeMenuListView) findViewById(R.id.contact_list);
		View newRequestHeader = View.inflate(getActivity(),R.layout.row_new_request_header_view,null);
		newRequestItem = (TextView) newRequestHeader.findViewById(R.id.new_requests);
		attentionContactListView.removeHeaderView(newRequestHeader);
		attentionContactListView.addHeaderView(newRequestHeader);
	}

	public void initView() {
		attentionContactListView.setMenuCreator(contactMenuCreator);
		attentionContactListView.setOnMenuItemClickListener(contactsMenuClickListener);
		attendeeList = AttendeeEntity.convertToContactEntity(DBHelper.getInstance().getAttendeesDao().getAllAttendee());
		attentionRequestList = ReceivedRequestEntity.convertToContactEntity(DBHelper.getInstance().getReceivedRequestDao().getAllRequest());
		measureMessageList = DBHelper.getInstance().getMessageDao().getAllMessage();
		attendeeAdapter = new AttentionWithBadgeAdapter(getActivity(),R.layout.row_attention_vertical,attendeeList,false);
		attentionContactListView.setAdapter(attendeeAdapter);
		attentionContactListView.setOnItemClickListener(onItemClickListener);
	}

	@Override
	public void onResume() {
		super.onResume();
		ansyncDataThread.stop();
		if(NetUtil.checkNetWork(getActivity())) ansyncDataThread.start();
	}

	private boolean isAnsyncAttendees = false;
	private void asyncAttendees(int startPage){
		if(isAnsyncAttendees) return;
		attendeeUpdated = false;
		isAnsyncAttendees = true;
		RestClient.getAuthedClient().getApiService().getAttendees(startPage,new Callback<GetAttendeesResponse>() {
			@Override
			public void success(GetAttendeesResponse getAttendeesResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取当前用户或提供者关注的用户列表-getAttendees》\n请求成功： \n\t返回数据：" + getAttendeesResponse.toString());
				final List<GetAttendeesResponse.ResultsEntity> attendees = getAttendeesResponse.getResults();
				if(attendees == null || attendees.size() == 0) return;
				for(GetAttendeesResponse.ResultsEntity attendee : attendees){
					AttendeeEntity attendeeEntity = new AttendeeEntity();
					attendeeEntity.atid = attendee.getAtid();
					attendeeEntity.attendeeId = attendee.getAttendee();
					attendeeEntity.attendeeName = attendee.getAttendee_name();
					attendeeEntity.attenderLevel = AttentionLevelView.ATTENTION_LEVEL.fromInt(attendee.getAttender_level());
					attendeeEntity.attendeeLevel = AttentionLevelView.ATTENTION_LEVEL.fromInt(attendee.getAttendee_level());
					ContactEntity contactEntity = AttendeeEntity.convertToContactEntity(attendeeEntity);
					if(!attendeeList.contains(contactEntity)){
						attendeeUpdated = true;
						attendeeList.add(contactEntity);
						DBHelper.getInstance().getAttendeesDao().insertAttendee(attendeeEntity);
					}
				}
				isAnsyncAttendees = false;
				if(getAttendeesResponse.getNext() != null && !getAttendeesResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getAttendeesResponse.getNext()).getQueryParameter("page"));
					asyncAttendees(nextPage);
				} else if(attendeeUpdated){
					attendeeAdapter.notifyDataSetChanged();
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取当前用户或提供者关注的用户列表-getAttendees》\n请求失败： \n\t错误信息：" + retrofitError.toString());
			}
		});
	}

	private boolean isAnsyncMessage = false;
	private void asyncMessage(int startPage){
		if(isAnsyncMessage) return;
		isAnsyncMessage = true;
		RestClient.getAuthedClient().getApiService().getAttenderMessage(startPage,1, new Callback<GetAttenderMessagesResponse>() {
			@Override
			public void success(GetAttenderMessagesResponse getAttenderMessagesResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取关注消息-getAttenderMessage》\n请求成功： \n\t返回数据：" + getAttenderMessagesResponse.toString());
				final List<GetAttenderMessagesResponse.ResultsEntity> messages = getAttenderMessagesResponse.getResults();
				if (messages == null || messages.size() == 0) return;
				for (GetAttenderMessagesResponse.ResultsEntity message : messages) {
					MeasureMessageEntity measureMessage = message.toMeasureMessageEntity();
					if(!measureMessageList.contains(measureMessage)){
						newMessageList.add(measureMessage);
						DBHelper.getInstance().getMessageDao().insertMessage(measureMessage);
					}
				}
				isAnsyncMessage = false;
				if(getAttenderMessagesResponse.getNext() != null && !getAttenderMessagesResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getAttenderMessagesResponse.getNext()).getQueryParameter("page"));
					asyncAttendees(nextPage);
				} else if(newMessageList.size() > 0){
					attendeeAdapter.setAllMessages(newMessageList);
					attendeeAdapter.notifyDataSetChanged();
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取关注消息-getAttenderMessage》\n请求失败： \n\t错误信息：" + retrofitError.toString());
			}
		});
	}

	private boolean isAnsyncRequest = false;
	private void asyncRequest(int startPage){
		if(isAnsyncRequest) return;
		isAnsyncRequest = true;
		RestClient.getAuthedClient().getApiService().getReceivedAttenderRequest(startPage,new Callback<GetReceivedAttenderRequestResponse>() {
			@Override
			public void success(GetReceivedAttenderRequestResponse getReceivedAttenderRequestResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取收到的关注请求-getReceivedAttenderRequest》\n请求成功： \n\t返回数据：" + getReceivedAttenderRequestResponse.toString());
				final List<GetReceivedAttenderRequestResponse.ResultsEntity> resultEntities = getReceivedAttenderRequestResponse.getResults();
				if (resultEntities == null || resultEntities.size() == 0) return;
				for (GetReceivedAttenderRequestResponse.ResultsEntity resultsEntity : resultEntities) {
					ReceivedRequestEntity requestEntity = new ReceivedRequestEntity();
					requestEntity.arId = resultsEntity.getAr_id();
					requestEntity.attendee = resultsEntity.getAttendee();
					requestEntity.attendeeName = resultsEntity.getAttendee_name();
					requestEntity.attendeeLevel = resultsEntity.getAttendee_level();
					requestEntity.status = resultsEntity.getStatus();
					ContactEntity contactEntity = ReceivedRequestEntity.convertToContactEntity(requestEntity);
					if(resultsEntity.getStatus() == ReceivedRequestEntity.STATUS_PENDING && !attentionRequestList.contains(contactEntity)){
						DBHelper.getInstance().getReceivedRequestDao().insertRequest(requestEntity);
						newAttentionRequests.add(contactEntity);
					}
				}
				isAnsyncRequest = false;
				if(getReceivedAttenderRequestResponse.getNext() != null && !getReceivedAttenderRequestResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getReceivedAttenderRequestResponse.getNext()).getQueryParameter("page"));
					asyncRequest(nextPage);
				} else if(newAttentionRequests.size() > 0){
					BadgeView badgeView = new BadgeView(getActivity(),newRequestItem);
					badgeView.setText(newAttentionRequests.size()+"");
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取收到的关注请求-getReceivedAttenderRequest》\n请求失败： \n\t错误信息：" + retrofitError.toString());
				T.showLong(getActivity(), R.string.get_data_from_webserver_failed);
			}
		});
	}

	private SwipeMenuListView.OnMenuItemClickListener contactsMenuClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
			switch (index) {
				case 0: //取消关注
					final int p = attendeeList.size()  - 1 - position; // 倒序显示
					final int attendId = attendeeList.get(p).id;
					final int level = AttentionLevelView.ATTENTION_LEVEL.NOTIFY_NOTHING.ordinal();
					RestClient.getAuthedClient().getApiService().putAttendees(attendId, new PutAttendeesRequest(level), new Callback() {
						@Override
						public void success(Object o, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(getActivity());
								T.showShort(getActivity(),R.string.nauthorized_and_relogin);
								return;
							}
							L.d("《修改关注-putAttendees》", "请求成功： \n\t返回数据：" + o.toString());
							if(response.getStatus() == 200) {
								attendeeList.remove(p);
								attendeeAdapter.notifyDataSetChanged();
							} else T.showLong(getActivity(), R.string.cancel_attention_failed);
						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《修改关注-putAttendees》", "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showLong(getActivity(), R.string.cancel_attention_failed);
						}
					});
					break;
			}
			return false;
		}
	};


	private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if(position == 0) startActivity(new Intent(getActivity(),ReceivedRequestActivity.class));
			else {
				String attendee = attendeeList.get(position - 1).contactPhoneNum;
				String attendeeName = attendeeList.get(position - 1).contactName;
				Intent intent = new Intent(getActivity(),MeasureMessageActivity.class);
				intent.putExtra(MeasureMessageActivity.KEY_ATTENDEE,attendee);
				intent.putExtra(MeasureMessageActivity.KEY_ATTENDEE_NAME,attendeeName);
				startActivity(intent);
			}
		}
	};

	SwipeMenuCreator contactMenuCreator = new SwipeMenuCreator() {

		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem inattentionBtn = new SwipeMenuItem(getActivity());
			Drawable inattentionBg = new ColorDrawable(getResources().getColor(R.color.orange_menu_bg_color));
			inattentionBtn.setBackground(inattentionBg);
			inattentionBtn.setWidth(DensityUtils.dp2px(getActivity(), 80));
			inattentionBtn.setTitle(R.string.inattention);
			inattentionBtn.setTitleSize(16);
			inattentionBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(inattentionBtn);
		}
	};


	class AnsyncDataThread implements Runnable {
		public boolean running = false;
		private Thread thread = null;

		public void run() {
			asyncAttendees(1);
			asyncMessage(1);
			asyncRequest(1);
		}

		public void start() {
			this.thread = new Thread(this);
			this.running = true;
			this.thread.start();
		}

		public void stop() {
			this.running = false;
			this.thread = null;
		}
	}

}
